const { Service } = require("egg");

class AwardKindService extends Service {
  async create(data) {
    const { ctx } = this;
    return await ctx.model.AwardKind.create(data).then((res) => {
      return res ? res.toJSON() : res;
    });
  }

  async findOne(where) {
    const { ctx } = this;
    return await ctx.model.AwardKind.findOne({ where: where }).then((res) => {
      return res ? res.toJSON() : res;
    });
  }

  async list() {
    const { ctx } = this;
    const datas = await ctx.model.AwardKind.findAll({
      raw: true,
      order: [["kindId", "ASC"]], // 根据 kindId 排序
      attributes: { exclude: [] }, // 如果不需要排除任何属性，则可以为空数组
    });
    return datas;
  }

  async update(where, updates) {
    const { ctx } = this;
    return await ctx.model.AwardKind.update(updates, {
      where,
    });
  }

  async delete(where) {
    const { ctx } = this;
    return await ctx.model.AwardKind.destroy({
      where,
    });
  }

  async setLatest(kindId) {
    const { ctx } = this;

    await ctx.model.AwardKind.update(
      { isLatest: 0 },
      { where: { isLatest: 1 } }
    );

    const result = await ctx.model.AwardKind.update(
      { isLatest: 1 },
      { where: { kindId } }
    );

    return result[0];
  }
}

module.exports = AwardKindService;
